package com.atguigu.lease.admin.service.impl;

import com.atguigu.lease.admin.mapper.*;
import com.atguigu.lease.admin.service.*;
import com.atguigu.lease.model.bean.*;
import com.atguigu.lease.model.enums.ItemTypeEnum;
import com.atguigu.lease.model.vo.apartment.*;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author YouKinn
 * @description 针对表【room_info(房间信息表)】的数据库操作Service实现
 * @createDate 2025-06-20 20:18:17
 */
@Service
public class RoomInfoServiceImpl extends ServiceImpl<RoomInfoMapper, RoomInfo>
        implements RoomInfoService {

    @Autowired//房间属性值
    private RoomAttrValueService roomAttrValueService;
    @Autowired//房间设施
    private RoomFacilityService roomFacilityService;
    @Autowired//房间标签
    private RoomLabelService roomLabelService;
    @Autowired//房间租赁期限
    private RoomLeaseTermService roomLeaseTermService;
    @Autowired//房间支付方式
    private RoomPaymentTypeService roomPaymentTypeService;
    @Autowired//杂费值信息
    private ApartmentFeeValueService apartmentFeeValueService;
    @Autowired//图
    private GraphInfoService graphInfoService;
    @Autowired
    ApartmentInfoService apartmentInfoService;

    @Resource
    RoomFacilityMapper roomFacilityMapper;
    @Resource
    RoomLabelMapper roomLabelMapper;
    @Resource
    RoomPaymentTypeMapper roomPaymentTypeMapper;
    @Resource
    RoomLeaseTermMapper roomLeaseTermMapper;
    @Resource
    RoomAttrValueMapper roomAttrValueMapper;

    // spring事务管理：默认出现RuntimeException才会回滚
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveOrUpdateRoomSubmitVo(RoomSubmitVo roomSubmitVo) {
        //1、在执行新增更新房间信息前 判断是新增还是更新
        boolean isUpdate = roomSubmitVo.getId() != null;
        //2、执行房间的新增更新
        this.saveOrUpdate(roomSubmitVo);
        //3、如果是更新：删除房间之前的配套 标签 等数据
        Long roomId = roomSubmitVo.getId();
        if (isUpdate) {
            //删除房间的属性值：
            roomAttrValueService.remove(Wrappers.lambdaQuery(RoomAttrValue.class)
                    .eq(RoomAttrValue::getRoomId, roomId));
            //删除房间的配套
            roomFacilityService.remove(Wrappers.lambdaQuery(RoomFacility.class)
                    .eq(RoomFacility::getRoomId, roomId));
            //删除房间的标签
            roomLabelService.remove(Wrappers.lambdaQuery(RoomLabel.class)
                    .eq(RoomLabel::getRoomId, roomId));
            //删除房间的租期
            roomLeaseTermService.remove(Wrappers.lambdaQuery(RoomLeaseTerm.class)
                    .eq(RoomLeaseTerm::getRoomId, roomId));
            //删除房间的支付方式
            roomPaymentTypeService.remove(Wrappers.lambdaQuery(RoomPaymentType.class)
                    .eq(RoomPaymentType::getRoomId, roomId));
            //删除房间的图片
            graphInfoService.remove(Wrappers.lambdaQuery(GraphInfo.class)
                    .eq(GraphInfo::getItemId, roomId)
                    .eq(GraphInfo::getItemType, ItemTypeEnum.ROOM));
        }

        //4、保存房间的配套 标签 等数据
        //保存房间的属性值
        List<RoomAttrValue> roomAttrValues = roomSubmitVo
                .getAttrValueIds()
                .stream()
                .map(attrValueId -> {
                    RoomAttrValue roomAttrValue = new RoomAttrValue();
                    roomAttrValue.setRoomId(roomId);
                    roomAttrValue.setAttrValueId(attrValueId);
                    return roomAttrValue;
                })
                .collect(Collectors.toList());


        roomAttrValueService.saveBatch(roomAttrValues);
        //保存房间的配套
        List<RoomFacility> roomFacilities = roomSubmitVo.getFacilityInfoIds().stream()
                .map(facilityInfoId -> {
                    RoomFacility roomFacility = new RoomFacility();
                    roomFacility.setRoomId(roomId);
                    roomFacility.setFacilityId(facilityInfoId);
                    return roomFacility;
                }).collect(Collectors.toList());

        roomFacilityService.saveBatch(roomFacilities);
        //保存房间的标签
        List<RoomLabel> roomLabels = roomSubmitVo.getLabelInfoIds().stream()
                .map(labelInfoId -> {
                    RoomLabel roomLabel = new RoomLabel();
                    roomLabel.setRoomId(roomId);
                    roomLabel.setLabelId(labelInfoId);
                    return roomLabel;
                }).collect(Collectors.toList());
        roomLabelService.saveBatch(roomLabels);

        //保存房间的租期
        List<RoomLeaseTerm> roomLeaseTerms = roomSubmitVo.getLeaseTermIds().stream()
                .map(leaseTermId -> {
                    RoomLeaseTerm roomLeaseTerm = new RoomLeaseTerm();
                    roomLeaseTerm.setRoomId(roomId);
                    roomLeaseTerm.setLeaseTermId(leaseTermId);
                    return roomLeaseTerm;
                }).collect(Collectors.toList());
        roomLeaseTermService.saveBatch(roomLeaseTerms);

        //保存房间的支付方式
        List<RoomPaymentType> roomPaymentTypes = roomSubmitVo.getPaymentTypeIds().stream()
                .map(paymentTypeId -> {
                    RoomPaymentType roomPaymentType = new RoomPaymentType();
                    roomPaymentType.setRoomId(roomId);
                    roomPaymentType.setPaymentTypeId(paymentTypeId);
                    return roomPaymentType;
                }).collect(Collectors.toList());
        roomPaymentTypeService.saveBatch(roomPaymentTypes);

        //保存房间的图片列表
        graphInfoService.saveBatch(
                roomSubmitVo
                        .getGraphVoList()
                        .stream()
                        .map(graphVo -> {
                            GraphInfo graphInfo = new GraphInfo();
                            BeanUtils.copyProperties(graphVo, graphInfo);
                            graphInfo.setItemType(ItemTypeEnum.ROOM.getCode());
                            graphInfo.setItemId(roomId);
                            return graphInfo;
                        }).collect(Collectors.toList())
        );


    }

    @Override
    public Page<RoomItemVo> getPageItem(Long current, Long size, RoomQueryVo queryVo) {
        return baseMapper.selectRoomItemVoPage(new Page<>(current, size), queryVo);
    }

    @Override
    public RoomDetailVo getDetailById(Long id) {
        RoomDetailVo roomDetailVo = new RoomDetailVo();
        //1、房间数据
        RoomInfo roomInfo = this.getById(id);
        BeanUtils.copyProperties(roomInfo, roomDetailVo);
        //2、配套: 配套和房间是N:N的关系，配套表无法直接保存配套所属房间的id   使用了中间表保存数据
        // 房间需要查询自己的配套： 先到中间表- room_facility表中查询房间的配套id列表，再根据配套id列表到facility_info表中查询配套列表
        roomDetailVo.setFacilityInfoList(roomFacilityMapper.selectFacilityInfosByRoomId(id));
        //3、标签数据
        roomDetailVo.setLabelInfoList(roomLabelMapper.selectLabelInfosByRoomId(id));
        //4、支付方式
        roomDetailVo.setPaymentTypeList(roomPaymentTypeMapper.selectPaymentTypesByRoomId(id));
        //5、租期
        roomDetailVo.setLeaseTermList(roomLeaseTermMapper.selectLeaseTermsByRoomId(id));
        //8、属性值
        roomDetailVo.setAttrValueVoList(roomAttrValueMapper.selectAttValueVosByRoomId(id));
        //6、图片:
        roomDetailVo.setGraphVoList(
                //到数据库中查询GraphInfo集合:房间的图片列表
                graphInfoService.list(Wrappers.lambdaQuery(GraphInfo.class)
                                .eq(GraphInfo::getItemId, id)
                                .eq(GraphInfo::getItemType, ItemTypeEnum.ROOM.getCode())
                        )
                        //                    将GraphInfo列表转为 GraphVo集合
                        .stream()
                        .map(graphInfo -> {
                            GraphVo graphVo = new GraphVo();
                            BeanUtils.copyProperties(graphInfo, graphVo);
                            return graphVo;
                        }).collect(Collectors.toList())
        );

        //7、公寓: 一个房间只属于一个公寓！
        ApartmentInfo apartmentInfo = apartmentInfoService.getById(roomInfo.getApartmentId());
        roomDetailVo.setApartmentInfo(apartmentInfo);

        return roomDetailVo;
    }

    @Override
    public List<RoomInfo> listBasicByApartmentId(Long apartmentId) {
        return baseMapper.selectBasicByApartmentId(apartmentId);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteRoomInfoById(Long id) {
        //1、删除房间数据
        this.removeById(id);
        //2、删除房间配套数据
        roomAttrValueService.remove(Wrappers.lambdaQuery(RoomAttrValue.class)
                .eq(RoomAttrValue::getRoomId, id));
        //删除房间的配套
        roomFacilityService.remove(Wrappers.lambdaQuery(RoomFacility.class)
                .eq(RoomFacility::getRoomId, id));
        //删除房间的标签
        roomLabelService.remove(Wrappers.lambdaQuery(RoomLabel.class)
                .eq(RoomLabel::getRoomId, id));
        //删除房间的租期
        roomLeaseTermService.remove(Wrappers.lambdaQuery(RoomLeaseTerm.class)
                .eq(RoomLeaseTerm::getRoomId, id));
        //删除房间的支付方式
        roomPaymentTypeService.remove(Wrappers.lambdaQuery(RoomPaymentType.class)
                .eq(RoomPaymentType::getRoomId, id));
        //删除房间的图片
        graphInfoService.remove(Wrappers.lambdaQuery(GraphInfo.class)
                .eq(GraphInfo::getItemId, id)
                .eq(GraphInfo::getItemType, ItemTypeEnum.ROOM));
    }
}





